package com.example.yangjintingtest.service;

import com.example.yangjintingtest.domain.BlogComment;
import com.example.yangjintingtest.domain.Comment;
import com.example.yangjintingtest.domain.Statistic;
import com.example.yangjintingtest.mapper.CommentMapper;
import com.example.yangjintingtest.mapper.CommentRepository;
import com.example.yangjintingtest.mapper.StatisticMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;
import java.util.Optional;

@Service
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;

    // 发表评论
    public void pushComment (BlogComment comment){
        commentMapper.pushComment (comment);
        // 更新文章评论数量
        Statistic statistic = statisticMapper.selectStatisticWithArticleId (comment.getArticleId ());
        statistic.setCommentsNum (statistic.getCommentsNum()+1);
        statisticMapper.updateArticleCommentsWithId (statistic);
    }
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    StatisticMapper statisticMapper;
    // 根据文章 id 获取评论
    public PageInfo<BlogComment> getComments(Integer aid, int page, int count) {
        PageHelper.startPage(page,count);
        List<BlogComment> commentList = commentMapper.selectCommentWithPage(aid);
        PageInfo<BlogComment> commentInfo = new PageInfo<>(commentList);
        return commentInfo;
    }

    // 根据评论id查询评论信息
    @Cacheable(cacheNames = "comment",unless = "#result==null")
    public Comment findById(int comment_id){
        Optional<Comment> optional = commentRepository.findById(comment_id);

        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }
    // 更新评论信息
    @Cacheable(cacheNames = "comment",key = "#result==null")
    public Comment updateComment(Comment comment){
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        return comment;
    }
    // 删除评论信息
    @Cacheable(cacheNames = "comment")
    public void deleteComment(int comment_id) { commentRepository.deleteById(comment_id); }
}